package com.example.project7.viewmodel;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.project7.model.LoginResponse;
import com.example.project7.model.RegisterResponse;
import com.example.project7.repository.AuthRepository;
import com.example.project7.utils.ApiResponse;
import com.example.project7.utils.SharedPreferencesUtil;

public class LoginViewModel extends AndroidViewModel {
    private static final String TAG = "LoginViewModel";
    
    private AuthRepository authRepository;
    private MutableLiveData<LoginState> loginStateLiveData = new MutableLiveData<>();
    private MutableLiveData<RegisterState> registerStateLiveData = new MutableLiveData<>();
    private MutableLiveData<AutoLoginState> autoLoginStateLiveData = new MutableLiveData<>();

    public LoginViewModel(@NonNull Application application) {
        super(application);
        authRepository = new AuthRepository(application.getApplicationContext());
    }

    public LiveData<LoginState> getLoginState() {
        return loginStateLiveData;
    }

    public LiveData<RegisterState> getRegisterState() {
        return registerStateLiveData;
    }

    public LiveData<AutoLoginState> getAutoLoginState() {
        return autoLoginStateLiveData;
    }

    /**
     * 执行登录操作
     *
     * @param email    邮箱
     * @param password 密码
     */
    public void login(String email, String password) {
        Log.d(TAG, "执行登录操作");
        loginStateLiveData.setValue(new LoginState.Loading());
        
        new Thread(() -> {
            try {
                ApiResponse<LoginResponse> response = authRepository.login(email, password);
                if (response.isSuccess()) {
                    // 登录成功
                    LoginState.Success successState = new LoginState.Success(response.getData());
                    loginStateLiveData.postValue(successState);
                } else {
                    // 登录失败
                    LoginState.Error errorState = new LoginState.Error(response.getErrorMessage());
                    loginStateLiveData.postValue(errorState);
                }
            } catch (Exception e) {
                Log.e(TAG, "登录过程中发生异常", e);
                LoginState.Error errorState = new LoginState.Error("登录过程中发生异常: " + e.getMessage());
                loginStateLiveData.postValue(errorState);
            }
        }).start();
    }

    /**
     * 执行注册操作
     *
     * @param email    邮箱
     * @param password 密码
     */
    public void register(String email, String password) {
        Log.d(TAG, "执行注册操作");
        registerStateLiveData.setValue(new RegisterState.Loading());
        
        new Thread(() -> {
            try {
                ApiResponse<RegisterResponse> response = authRepository.register(email, password);
                if (response.isSuccess()) {
                    // 注册成功
                    RegisterState.Success successState = new RegisterState.Success(response.getData());
                    registerStateLiveData.postValue(successState);
                } else {
                    // 注册失败
                    RegisterState.Error errorState = new RegisterState.Error(response.getErrorMessage());
                    registerStateLiveData.postValue(errorState);
                }
            } catch (Exception e) {
                Log.e(TAG, "注册过程中发生异常", e);
                RegisterState.Error errorState = new RegisterState.Error("注册过程中发生异常: " + e.getMessage());
                registerStateLiveData.postValue(errorState);
            }
        }).start();
    }

    /**
     * 执行自动登录检查
     */
    public void autoLogin() {
        Log.d(TAG, "执行自动登录检查");
        autoLoginStateLiveData.setValue(new AutoLoginState.Loading());
        
        // 检查是否启用了自动登录
        boolean autoLoginEnabled = SharedPreferencesUtil.getAutoLogin(getApplication().getApplicationContext());
        if (!autoLoginEnabled) {
            Log.d(TAG, "自动登录未启用");
            autoLoginStateLiveData.postValue(new AutoLoginState.NotEnabled());
            return;
        }
        
        new Thread(() -> {
            try {
                ApiResponse<String> response = authRepository.autoLogin();
                if (response.isSuccess()) {
                    // 自动登录成功
                    autoLoginStateLiveData.postValue(new AutoLoginState.Success());
                } else {
                    // 自动登录失败
                    autoLoginStateLiveData.postValue(new AutoLoginState.Error(response.getErrorMessage()));
                }
            } catch (Exception e) {
                Log.e(TAG, "自动登录过程中发生异常", e);
                autoLoginStateLiveData.postValue(new AutoLoginState.Error("自动登录过程中发生异常: " + e.getMessage()));
            }
        }).start();
    }

    /**
     * 保存自动登录状态
     *
     * @param autoLogin 是否启用自动登录
     */
    public void saveAutoLoginState(boolean autoLogin) {
        SharedPreferencesUtil.saveAutoLogin(getApplication().getApplicationContext(), autoLogin);
    }

    /**
     * 执行退出登录操作
     */
    public void logout() {
        authRepository.logout();
    }
}